#include "Parser.h"

#include<iostream>
using std::cout; 
using std::endl;

Parser::Parser(const_iterator begin, const_iterator end)
{		
	root = parserExpr(begin, end);		
} 

TokenNode* Parser::parserExpr(const_iterator begin, const_iterator end)
{
    size_t pos=0;		
	return addExpr(begin, end, pos);
}    

TokenNode* Parser::addExpr(const_iterator begin, const_iterator end, size_t & pos)
{
    TokenNode* l=multExpr(begin, end, pos);		
	if (((begin+pos)!=end) &&(((begin+pos+1)->getText()=="+") || ((begin+pos+1)->getText()=="-")))
    {
        pos+=2;               
        const_iterator temp=(begin+pos-1); 
		TokenNode* r=addExpr(begin, end, pos);				
        TokenNode* p=new TokenNode(*temp, l, r);
        return p; 				           
    }
    return l; 			
}
    
TokenNode* Parser::multExpr(const_iterator begin, const_iterator end, size_t & pos)
{
    TokenNode* l=atomExpr(begin, pos);		
    if (((begin+pos)!=end)&&(((begin+pos+1)->getText()=="*") || ((begin+pos+1)->getText()=="/")))	
	{
		pos+=2;
		const_iterator temp=(begin+pos-1);           
		TokenNode* r=multExpr(begin, end, pos);			
		TokenNode* p=new TokenNode(*temp, l, r);
		return p;			        
	}	
   	return l;			
}

TokenNode * Parser::atomExpr(const_iterator begin, size_t & pos)
{         
	return new TokenNode(*(begin+pos), 0, 0);
}
    
void Parser::deleteNode(TokenNode const* p)
{
	if (p)
    {
		deleteNode (p->getLeft());
	    deleteNode (p->getRight());
		delete p;
	}		
}

TokenNode const * Parser::getRoot()
{
    return root;
}

Parser::~Parser()
{
	deleteNode(root);
}

void printNode (TokenNode const* p)
	{
		if (p->getLeft()!=0)
			printNode (p->getLeft());
		std::cout << p->getData().getText()<< " ";
		if (p->getRight()!=0)
			printNode (p->getRight());		
	}
	
